<script setup>
const props = defineProps({
  value: {
    type: [Number, String],
    default: 0,
  },
})
const show = ref(parseFloat(props.value) || 0)
onMounted(() => {
  setTimeout(() => animation(0, parseFloat(props.value) || 0), 500)
  setInterval(() => animation(0, parseFloat(props.value) || 0), 8000)
})

function judgeFloat(from, to) {
  if (from % 1 !== 0 || to % 1 !== 0) {
    return 2
  }
  return 0
}

function animation(from, to, duration = 2000) {
  let number = from
  const start = Date.now()
  const speed = (to - from) / duration

  function _run() {
    const t = Date.now() - start
    if (t >= duration) {
      number = to
      show.value = number
      return
    }
    number = (from + t * speed).toFixed(judgeFloat(from, to))
    show.value = number
    requestAnimationFrame(_run)
  }

  _run()
}
function formatter(number) {
  if (number.toString().includes('.')) {
    const [integer, decimal] = number.toString().split('.')
    const numbers = integer.toString().split('').reverse()
    const segs = []
    while (numbers.length) segs.push(numbers.splice(0, 3).join(''))
    return segs.join(',').split('').reverse().join('') + '.' + decimal
  } else {
    const numbers = number.toString().split('').reverse()
    const segs = []

    while (numbers.length) segs.push(numbers.splice(0, 3).join(''))

    return segs.join(',').split('').reverse().join('')
  }
}
</script>
<template>
  <span>
    {{ formatter(show) }}
  </span>
</template>
